// /router/index.js
import { createRouter, createWebHistory } from "vue-router";
import LoginView from '../views/LoginView.vue';
import HomeView from '../views/HomeView.vue';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            component: HomeView
        },
        {
            path: '/Home',
            name: 'home',
            component: HomeView
        },
        {
            path: '/Login',
            name: 'login',
            component: LoginView
        },
        {
            path: '/Admin',
            name: 'admin',
            meta: { requireAuth: true }, // 等会靠它判断要不要验证登录
            component: () => import('../views/AdminView.vue'),
            children: [
                {
                    path: 'Main',
                    name: 'main',
                    component: () => import('../views/AdminMainView.vue')
                },
                {
                    path: 'Menu',
                    name: 'menu',
                    component: () => import('../views/AdminMenuView.vue')
                },
            ]
        },
        {
            path: '/:pathMatch(.*)',
            name: '404',
            component: () => import('../views/NotFoundView.vue')
        }
    ]
})

// 登录权限验证
router.beforeEach((to, from) => {
    const isLogin = window.localStorage.getItem('login');
    // 当路由记录的meta.requireAuth为true，就给requireAuth赋值true
    // to.matched是一个数组，some是js自带的方法，用于检查数组中是否有元素满足某个条件
    // const requireAuth = to.matched.some(r => r.meta.requireAuth == true);
    console.log(to.meta, isLogin)
    if (to.meta.requireAuth && isLogin !== 'ok') {
        // 跳转到登录页面，登录成功后可以借此跳转回来
        return {
            path: '/Login',
            query: { redirect: to.fullPath }
        }
        // return '/Login';
    }
})

export default router